<template>
  <div class="add-fee-con">
    <div class="left">
      <div class="title-bar">基础信息</div>
      <a-form ref="formRef" :model="form" auto-label-width>
        <a-form-item field="name" label="模板名称：" :rules="rules.name">
          <a-input v-model="form.name" placeholder="请输入模板名称" allow-clear />
        </a-form-item>
        <a-form-item field="shipLevel" label="物流优先级：" :rules="rules.shipLevel">
          <a-select placeholder="请选择" v-model="form.shipLevel">
            <a-option label="普通" value="Standard"></a-option>
            <a-option label="加急" value="Expedited"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="chargeType" label="计费维度：" :rules="rules.chargeType">
          <a-select placeholder="请选择" v-model="form.chargeType">
            <a-option label="按毛重" value="WEIGHT"></a-option>
            <a-option label="按体积" value="VOLUME"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="chargeMethod" label="计费方式：" :rules="rules.chargeMethod">
          <a-select placeholder="请选择" v-model="form.chargeMethod">
            <a-option label="首重续重" value="FIRST_CONTINUE"></a-option>
            <a-option label="重量段" value="RANGE"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="币种：">
          <a-select placeholder="请选择" v-model="form.currency" allow-clear allow-search>
            <a-option v-for="(key, value) in currencyList" :label="key" :value="value"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="体积参数：" v-if="form.chargeType == 'VOLUME'">
          <a-input v-model="form.volumeParam" placeholder="请输入体积参数" allow-clear></a-input>
        </a-form-item>
        <a-form-item label="费用折扣：">
          <a-input v-model="form.discount" placeholder="请输入费用折扣" allow-clear>
            <template #suffix> % </template>
          </a-input>
        </a-form-item>
        <a-form-item label="目的地：">
          <a-select v-model="form.countryCodeList" @change="selCountry" placeholder="请选择国家" :max-tag-count="1" multiple allow-clear allow-search>
            <a-option v-for="item of countriesOptions" :value="item.short">{{ item.name }}-{{ item.short }}</a-option>
          </a-select>
        </a-form-item>
      </a-form>

      <div class="title-bar">费用选项</div>

      <a-checkbox-group v-model="form.feeSel">
        <div class="clearfix">
          <a-checkbox-group @change="selFeeOption" direction="vertical" v-model="feeOptionSelArr">
            <div class="fl" v-for="item of feeOptionList" style="width: 120px; margin-bottom: 5px">
              <a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
            </div>
          </a-checkbox-group>
        </div>
      </a-checkbox-group>
    </div>
    <div class="right">
      <div class="title-bar">发货仓</div>
      <a-table :data="houseList" :pagination="false" @selection-change="selHouse" size="mini" class="table-singe-line" row-key="id" v-model:selected-keys="ids" :row-selection="rowSelection" :scroll="{ y: '300px' }">
        <template #columns>
          <a-table-column title="仓库ID" #cell="{ record }">
            {{ record.warehouseCode }}
          </a-table-column>
          <a-table-column title="仓库名称" #cell="{ record }">
            {{ record.warehouseName }}
          </a-table-column>
          <a-table-column title="状态" #cell="{ record }">
            {{ record.status == 1 ? '启用' : '停用' }}
          </a-table-column>
          <a-table-column title="存货类型" #cell="{ record }">
            {{ record.stockType }}
          </a-table-column>
          <a-table-column title="仓库属性" #cell="{ record }">
            {{ record.warehouseAttribute == 1 ? '国内仓' : '海外仓' }}
          </a-table-column>
        </template>
      </a-table>
      <div v-if="form.chargeMethod" style="display: flex; height: 30px; line-height: 30px; margin: 10px 0">
        <div class="title-bar">设置费用</div>
        <div class="ml10">计费维度：{{ form.chargeType == 'WEIGHT' ? '按毛重' : '按体积' }}</div>
        <div class="ml10">计费方式：{{ form.chargeMethod == 'FIRST_CONTINUE' ? '首重续重' : '重量段' }}</div>
      </div>
      <a-table size="mini" v-if="form.chargeMethod == 'FIRST_CONTINUE'" class="table-two-line" :data="firstContinueConfigList" :pagination="false" :scroll="{ y: 'calc(100vh - 588px)' }">
        <template #columns>
          <a-table-column title="重量范围" #cell="{ record }" :width="180">
            <div style="display: flex">
              <a-input-number v-model="record.minWeight" hide-button>
                <template #suffix> KG </template>
              </a-input-number>
              <span style="line-height: 32px">~</span>
              <a-input-number v-model="record.maxWeight" hide-button>
                <template #suffix> KG </template>
              </a-input-number>
            </div>
          </a-table-column>
          <a-table-column v-for="item of feeTitleOption" :title="item.label" :width="380" align="center">
            <template #title>
              <div>{{ item.label }}</div>
              <div>
                <span style="display: inline-block; width: 180px; text-align: center">首重/费用</span>
                <span style="display: inline-block; width: 180px; text-align: center">续重计重/续重单价</span>
              </div>
            </template>

            <template #cell="{ record }">
              <div style="display: flex">
                <div>
                  <div style="display: flex">
                    <a-input-number v-model="record[item.value].firstWeight" hide-button>
                      <template #suffix> KG </template>
                    </a-input-number>
                    <a-input-number v-model="record[item.value].firstAmount" hide-button>
                      <template #prefix> ￥ </template>
                    </a-input-number>
                  </div>
                </div>
                <div class="ml10">
                  <div style="display: flex">
                    <a-input-number v-model="record[item.value].continueWeight" hide-button>
                      <template #suffix> KG </template>
                    </a-input-number>
                    <a-input-number v-model="record[item.value].continueUnitAmount" hide-button>
                      <template #prefix> ￥ </template>
                    </a-input-number>
                  </div>
                </div>
              </div>
            </template>
          </a-table-column>
          <a-table-column title="操作" #cell="{ record, rowIndex }" :width="80">
            <a-button type="text" @click="initData('1')">新增</a-button>
            <a-button v-if="rowIndex > 0" type="text" style="color: red; margin-left: 5px" @click="firstContinueConfigList.splice(rowIndex, 1)">移除</a-button>
          </a-table-column>
        </template>
      </a-table>
      <a-table size="mini" v-if="form.chargeMethod == 'RANGE'" class="table-two-line" :data="rangConfigList" :pagination="false" :scroll="{ y: 'calc(100vh - 588px)' }">
        <template #columns>
          <a-table-column title="重量范围" #cell="{ record }" :width="180">
            <div style="display: flex">
              <a-input-number v-model="record.minWeight" hide-button>
                <template #suffix> KG </template>
              </a-input-number>
              <span style="line-height: 32px">~</span>
              <a-input-number v-model="record.maxWeight" hide-button>
                <template #suffix> KG </template>
              </a-input-number>
            </div>
          </a-table-column>
          <a-table-column v-for="item of feeTitleOption" :title="item.label" #cell="{ record }" :width="180">
            <a-input-number v-model="record[item.value].amount" hide-button>
              <template #prefix> ￥ </template>
            </a-input-number>
          </a-table-column>
          <a-table-column title="操作" #cell="{ record, rowIndex }" :width="80">
            <a-button type="text" @click="initData('2')">新增</a-button>
            <a-button v-if="rowIndex > 0" type="text" style="color: red; margin-left: 5px" @click="rangConfigList.splice(rowIndex, 1)">移除</a-button>
          </a-table-column>
        </template>
      </a-table>

      <div style="position: fixed; bottom: 20px; right: 30px">
        <a-button class="gray-outline" @click="back">取消</a-button>
        <a-button class="ml10" type="primary" :loading="btnLoading" @click="handleOk">保存</a-button>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import { currencySymbol } from '@/utils/globalData'
  import { countriesOptions } from '@/utils/countries'
  import { warehouiseAllList } from '@/api/warehouse'
  import { saveOrUpdateExpressFreightTemplate, getExpressFreightTemplateById } from '@/api/warehouse'
  import { Message } from '@arco-design/web-vue'
  import { useVisitedRoutesContext } from '@/store/modules/visited-routes'
  import { useRoute, useRouter } from 'vue-router'
  import _ from 'lodash-es'
  export default defineComponent({
    setup() {
      const formRef = ref()
      const visitedStore = useVisitedRoutesContext()
      const route = useRoute()
      const router = useRouter()
      const data: any = reactive({
        form: {
          chargeMethod: 'FIRST_CONTINUE',
        },
        rules: {
          name: [{ required: true, message: '请输入模板名称' }],
          shipLevel: [{ required: true, message: '请选择物流优先级' }],
          chargeType: [{ required: true, message: '请选择计费维度' }],
          chargeMethod: [{ required: true, message: '请选择计费方式' }],
        },
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        currencyList: currencySymbol,
        countriesOptions: countriesOptions,
        houseList: [],
        ids: [],
        firstContinueConfigList: [],
        rangConfigList: [],
        feeOptionList: [
          { label: '基础运费', value: 'basic' },
          { label: '挂号费', value: 'registration' },
          { label: '燃油费', value: 'fuel' },
          { label: '操作费', value: 'hand' },
          { label: '附加费', value: 'additional' },
          { label: '报关佣金费', value: 'commission' },
          { label: '其他费用', value: 'other' },
        ],
        feeTitleOption: [],
        feeOptionSelArr: [],
        btnLoading: false,
      })

      const getHouseList = async () => {
        const res = await warehouiseAllList()
        data.houseList = res?.data || []
      }

      // const addItem = (type: string) => {
      //   let obj = {}
      //   if (type == '1') {
      //     data.weightData.push(obj)
      //   } else {
      //     data.weightData1.push(obj)
      //   }
      // }

      const selFeeOption = (arr: any) => {
        data.feeTitleOption = []
        arr.forEach((e: any) => {
          let item = data.feeOptionList.find((el: any) => e == el.value)
          if (item) data.feeTitleOption.push(item)
        })
      }

      const initData = (type?: string) => {
        let obj = {
          maxWeight: 0,
          minWeight: 0,
          additional: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          basic: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          commission: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          fuel: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          hand: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          other: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
          registration: {
            amount: 0,
            continueUnitAmount: 0,
            continueWeight: 0,
            firstAmount: 0,
            firstWeight: 0,
          },
        }
        if (type == 'double') {
          data.firstContinueConfigList.push(obj)
          data.rangConfigList.push(obj)
        } else if (type == '1') {
          data.firstContinueConfigList.push(obj)
        } else {
          data.rangConfigList.push(obj)
        }
      }

      const selHouse = (ids: any) => {
        let arr = []
        ids.forEach((e: string) => {
          let item = data.houseList.find((el: any) => el.id == e)
          if (item) {
            let obj = {
              code: item.warehouseCode,
              id: item.id,
              name: item.warehouseName,
            }
            arr.push(obj)
          }
        })
        data.form.warehouseList = arr
        console.log(data.form)
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            if (!data.ids[0]) {
              return Message.error('请选择发货仓')
            }
            let params: any = [
              {
                ...data.form,
                addressesList: [],
                configKeyList: data.feeOptionSelArr,
                firstContinueConfigList: data.firstContinueConfigList,
                rangConfigList: data.rangConfigList,
              },
            ]

            if (data.form.countryCodeList) {
              data.form.countryCodeList.forEach((e: string) => {
                let obj = {
                  countryCode: e,
                }
                params[0].addressesList.push(obj)
              })
            }
            data.btnLoading = true
            const res: any = saveOrUpdateExpressFreightTemplate(params)
            data.btnLoading = false
            if (res) {
              let { type, id } = route.query
              type == 'add' ? Message.success('添加运费模板成功') : Message.success('运费模板编辑成功')
              back()
            }
          }
        })
      }

      const back = () => {
        visitedStore.removeVisitedRoute(route)
        router.push('/warehouse/logisticsSetting/feeTempalte/feeTempalte')
      }

      const init = () => {
        let { type, id } = route.query
        if (type == 'add') {
          initData('double')
        } else {
          getDetail(id)
        }
      }

      const getDetail = async (id: any) => {
        const res: any = await getExpressFreightTemplateById({ id })
        let item: any = res?.data || []
        data.feeOptionSelArr = item?.configKeyList || []
        selFeeOption(data.feeOptionSelArr)
        data.firstContinueConfigList = item?.firstContinueConfigList || []
        data.rangConfigList = item?.rangConfigList || []
        let wareHouseList = item?.warehouseList || []
        data.ids = wareHouseList.map((e: any) => e.id)

        let info: any = _.cloneDeep(item)
        delete info.wareHouseList
        delete info.firstContinueConfigList
        delete info.rangConfigList
        delete info.configKeyList
        data.form = info
        if (item.addressesList && item.addressesList[0]) {
          let arr: any = []
          item.addressesList.forEach((e: any) => {
            arr.push(e.countryCode)
          })
          data.form.countryCodeList = arr
        }
      }
      init()
      getHouseList()

      return {
        ...(toRefs(data) as any),
        formRef,
        // addItem,
        selFeeOption,
        initData,
        selHouse,
        handleOk,
        back,
        // selCountry,
      }
    },
  })
</script>

<style lang="less" scoped>
  .add-fee-con {
    width: 100%;
    height: calc(100vh - @menuHeight);
    // background-color: white;
    display: flex;
    .left {
      width: 400px;
      height: 100%;
      background-color: white;
      padding: 5px 10px;
      box-sizing: border-box;
    }
    .right {
      margin-left: 5px;
      background-color: white;
      width: calc(100% - 400px);
      padding: 5px 10px;
      box-sizing: border-box;
    }
  }
</style>
